<template>
  <div class="root">
    <div class="tree">
      <tree-aside @click-child="handleClickChild"></tree-aside>
      <router-view></router-view>
    </div>
    <div class="body-wrapper">
      <a-button id="btn" type="primary" @click="$router.push('/home/peopleRejister')">人工注册</a-button>
      <header>
        <div class="bodyTop">
          <div class="bodyTop2">
            <a-button :disabled="activeClass1" :class="{ activeClass: !activeClass1, issue: true }" @click="allIssue()">批量发布</a-button>&nbsp;
            <a-button :disabled="activeClass2" :class="{ activeClass: !activeClass2, pause: true }" @click="allpause()">批量停用</a-button>
            <a-button :disabled="activeClass1" :class="{ activeClass: !activeClass1, issue: true }" @click="allSort()">批量分类</a-button>
          </div>
          <!-- 查询 -->
          &nbsp;
          <span class="select">
            <h4>接口来源:</h4>
            <a-select ref="select" v-model:value="searchconditions.selectValue" :options="sources" style="width: 120px">
              <!-- <a-select-option v-for="(item, num) in sources" :key="num" :value="item.portsSource">{{ item.portsSource }}</a-select-option> -->
            </a-select>
          </span>
          <span class="select">
            <h4>API状态:</h4>
            <a-select ref="select" v-model:value="searchconditions.selectValue2" :options="options" style="width: 120px"> </a-select>
          </span>

          <span class="select">
            <h4>接口名称:</h4>
            <a-input v-model:value="searchconditions.inputValue" placeholder="请输入码表名称" />
          </span>
          <a-button @click="reset">重置</a-button>
          <a-button id="btn2" type="primary" @click="search">查询</a-button>
        </div>
      </header>
      <br />

      <!-- 表格 -->
      <div class="relative py-8">
        <a-table
          :data-source="dataSource"
          :pagination="pagination"
          :row-selection="{ selectedRowKeys: selectedRowKeys1, onChange: selectChangEtion }"
          :row-key="(record: any) => { return record.portsId }"
        >
          <a-table-column key="portsId" title="接口名称" :width="130">
            <template #default="{ column, record }">
              <template v-if="column.key === 'portsId'">
                <a @click="showModalName(record.portsId)">
                  {{ record.portsName }}
                </a>
              </template>
            </template>
          </a-table-column>
          <a-table-column key="portsMsg" data-index="portsMsg" :width="120">
            <template #title><span>接口描述</span></template>
          </a-table-column>
          <a-table-column key="dirName" data-index="dirName" :width="130">
            <template #title><span>接口分类</span></template>
          </a-table-column>
          <a-table-column key="portsSource" data-index="portsSource" :width="130">
            <template #title><span>接口来源</span></template>
          </a-table-column>
          <a-table-column key="portsStatus" data-index="portsStatus" :width="90">
            <template #title><span>API状态</span></template>
            <template #default="{ record }">
              <span>
                <a-tag :color="Colors[record.portsStatus]">{{ Status[record.portsStatus] }}</a-tag>
              </span>
            </template>
          </a-table-column>
          <a-table-column
            key="modifyTime"
            :width="160"
            data-index="modifyTime"
            :sorter="
            (a: DataItem, b: DataItem) => {
              return a.modifyTime > b.modifyTime ? 1 : -1;
            } "
          >
            <template #title><span>更新时间</span></template>
          </a-table-column>
          <a-table-column key="action" title="操作" :width="260">
            <template #default="{ text: record }">
              <span>
                <template v-if="record.portsStatus">
                  <a-button type="primary" size="small" @click="showModalInter(record.portsId)">接口测试</a-button>
                </template>
                <template v-if="record.portsStatus == 2">
                  <a-popconfirm title="请确认是否停用该码表？" ok-text="是" cancel-text="否" @confirm="confirm3(record.portsId)"> <a-button type="primary" size="small">停用</a-button></a-popconfirm>
                </template>
                <template v-else-if="record.portsStatus == 3">
                  <a-popconfirm title="请确认是否发布该码表？" ok-text="是" cancel-text="否" @confirm="confirm2(record.portsId)"> <a-button type="primary" size="small">发布</a-button></a-popconfirm>
                  <a-button type="primary" size="small" @click="$router.push({ path: '/home/peopleRejister', query: { portsId: record.portsId } })">编辑</a-button>
                </template>
                <template v-else-if="record.portsStatus != 3">
                  <a-popconfirm title="请确认是否发布该码表？" ok-text="是" cancel-text="否" @confirm="confirm2(record.portsId)">
                    <a-button type="primary" size="small">发布</a-button>
                  </a-popconfirm>
                  <a-button type="primary" size="small" @click="$router.push({ path: '/home/peopleRejister', query: { portsId: record.portsId } })">编辑</a-button>
                  <a-popconfirm v-if="dataSource.length" title="请确认是否删除该码表？" ok-text="是" cancel-text="否" @confirm="confirm1(record.portsId)">
                    <a-button type="primary" size="small">删除</a-button></a-popconfirm
                  >
                </template>
              </span>
            </template>
          </a-table-column>
        </a-table>
      </div>
    </div>
  </div>

  <!-- 名字弹窗 -->
  <inter-face-name v-model:visible="visibleName" :post-id-name="postIdName" @change-show="ChangeShow"> </inter-face-name>
  <!-- 接口测试按钮弹窗   -->
  <inter-face-test v-model:visible="visibleTnter" :post-id-name="postIdName" @change-show1="ChangeShowInter"></inter-face-test>
  <!-- 批量分类弹窗 -->
  <all-dir-divide v-model:visible="visibleDir" :select-list="name" :selected-row-keys1="selectedRowKeys1" @change-show-dir="changeShowDir" @click-new="clickNew"></all-dir-divide>
</template>
<script setup lang="ts">
  import { ref, onMounted } from 'vue';
  import type { Ref } from 'vue';
  import { Status, Colors } from '@/pages/enumType/enum';
  import { message } from 'ant-design-vue';
  import interFaceName from './component/interFaceName.vue';
  import interFaceTest from './component/interfaceTest.vue';
  import treeAside from './component/treeAside.vue';
  import allDirDivide from './component/allDirDivide.vue';
  import { DataItem, conditionsType } from './type/index';
  import { getData, getinterFace, delData, pauseAndIssueAllStatus, interFace, editBatchClassify, selectDir, selectDirData } from '@/api/test/interFace';
  //查询所有数据
  const dataSource: Ref<DataItem[]> = ref([]);
  let totalData = ref();
  let pageNum = ref<number>(0);
  let pageSize = ref<number>(0);
  const sources = ref();
  onMounted(async () => {
    // 接口分类
    const resgetinterFace = await getinterFace();
    // treeDatas.value = handleTreeDatas(resgetinterFace.data);
    //下拉框接口来源
    const resinterFace = await interFace();
    console.log('xxxx', resinterFace);
    sources.value = resinterFace.data.map((item: any) => {
      return { label: item.portsSource, value: item.portsSource };
    });
    const resgetData = await getData({});
    dataSource.value = resgetData.data.list;
    totalData.value = resgetData.data.total;
    pageNum.value = resgetData.data.pageNum;
    pageSize.value = resgetData.data.pageSize;
    // dataSource.value.forEach(() => {

    // });
    // 平铺数组;
    for (let item of dataSource.value) {
      if (item.children) {
        for (let i of item.children) {
          dataSource.value.push(i);
        }
        delete item['children'];
        // handle(rs);
      }
    }
  });

  //中间部分的头部
  const searchconditions: conditionsType = reactive({
    selectValue: '请选择',
    selectValue2: '请选择',
    inputValue: '',
  });
  const reset = async () => {
    searchconditions.selectValue = '请选择';
    searchconditions.selectValue2 = '请选择';
    searchconditions.inputValue = '';
    const resgetData = await getData({});
    if (resgetData.code == 100200) {
      message.success('重置成功');
    }
    dataSource.value = resgetData.data.list;
    totalData.value = resgetData.data.total;
    pageNum.value = resgetData.data.pageNum;
    pageSize.value = resgetData.data.pageSize;
  };
  // 码表状态下拉框数据
  const options = [
    { value: 1, label: '未发布' },
    { value: 2, label: '已发布' },
    { value: 3, label: '已停用' },
  ];
  //表格数据

  // 查询接口开始
  const search = async () => {
    let data: {
      portsName?: string;
      pageSize?: number;
      portsSource?: string;
      portsStatus?: number;
      pageNum: number;
    };
    // 模糊查询
    let selectStatus = parseInt(searchconditions.selectValue2);
    if (searchconditions.inputValue != '' && searchconditions.selectValue == '请选择' && searchconditions.selectValue2 == '请选择') {
      data = { portsName: searchconditions.inputValue, pageNum: pageNum.value };
    } else if (searchconditions.inputValue == '' && searchconditions.selectValue != '请选择' && searchconditions.selectValue2 == '请选择') {
      data = { pageNum: pageNum.value, portsSource: searchconditions.selectValue };
    } else if (searchconditions.inputValue == '' && searchconditions.selectValue == '请选择' && searchconditions.selectValue2 != '请选择') {
      data = { pageNum: pageNum.value, portsStatus: selectStatus };
    } else {
      data = {
        portsSource: searchconditions.selectValue,
        portsStatus: selectStatus,
        portsName: searchconditions.inputValue,
        pageSize: pageSize.value,
        pageNum: pageNum.value,
      };
    }
    // console.log(data, '查询');
    const resgetData = await getData(data);
    console.log(resgetData, 'ZZZ查询接口');
    if (resgetData.code == 100200) {
      message.success('查询成功');
      dataSource.value = resgetData.data.list;
    }
  };
  // 查询接口结束

  //全选选择框
  //三个批量按钮
  const activeClass1 = ref<boolean>(true);
  const activeClass2 = ref<boolean>(true);
  //选中的id
  let selectedRowKeys1: Ref<number[]> = ref([]);
  //选中的一条数据的名称
  let name = ref();
  const arrPause: Ref<number[]> = ref([]); //停用数组
  const arrIssue: Ref<number[]> = ref([]); //发布数组
  const selectChangEtion = (selectedRowKeys: number[], selectedRows: DataItem[]) => {
    selectedRowKeys1.value = selectedRowKeys;
    name.value = selectedRows;
    selectedRows.forEach((item: { portsName: String }) => {
      name.value = item.portsName;
    });

    // console.log(selectedRows, 'select111');
    let pauseCount = 0;
    let IssueCount = 0;
    activeClass1.value = true; //发布按钮变为禁用
    activeClass2.value = true; //停用按钮变为禁用
    // 1未发布 2 已发布 3 已停用
    if (selectedRows.length >= 1) {
      selectedRows.forEach(item => {
        if (item.portsStatus != 2) {
          pauseCount += 1; //记下一个可以发布的
          arrIssue.value.push(item.portsId);
        } else {
          IssueCount += 1; // 记下一个可以停用的
          arrPause.value.push(item.portsId);
        }
      });
      if (pauseCount >= 1) {
        activeClass1.value = false; //发布按钮变为可用
      } else if (IssueCount >= 1) {
        activeClass2.value = false; //停用按钮变为可用
      }
    }
    selectedRowKeys = [];
  };

  //名字弹窗
  // let newData = ref<string>('');
  const visibleName = ref<boolean>(false);
  const postIdName = ref(1); // const dataTable = ref<Object>('');
  const showModalName = (portsId: number) => {
    visibleName.value = true;
    postIdName.value = portsId;
  };
  const ChangeShow = (show: string) => {
    // 子组件向外触发父组件事件“关闭”新增码表弹窗
    if (show == 'false') {
      visibleName.value = false;
    }
  };

  // 测试接口弹窗
  const visibleTnter = ref<boolean>(false);
  const showModalInter = (portsId: number) => {
    visibleTnter.value = true;
    postIdName.value = portsId;
  };
  const ChangeShowInter = (show: string) => {
    // 子组件向外触发父组件事件“关闭”新增码表弹窗
    if (show == 'false1') {
      visibleTnter.value = false;
    }
  };

  //批量分类弹窗
  const visibleDir = ref<boolean>(false);
  const allSort = () => {
    visibleDir.value = true;
  };
  const changeShowDir = (show: string) => {
    // 子组件向外触发父组件事件“关闭”新增码表弹窗
    if (show == 'false') {
      visibleDir.value = false;
    }
  };
  const clickNew = (Newdata: { dirName: string; dirId: number }) => {
    // dataSource.value.forEach(item => {
    //   item.dirId = Newdata.dirId;
    //   item.dirName = Newdata._value.dirName;
    // console.log(Newdata._value.dirName, '0000000');
    // });
    selectedRowKeys1.value.forEach((i: number) => {
      dataSource.value.filter(item => {
        if (item.portsId == i) {
          item.dirId = Newdata.dirId;
          item.dirName = Newdata._value.dirName;
        }
      });
    });
  };

  //目录部分
  let dirIds = ref<number>(0); //记住当前所在接口分类的Id
  const handleClickChild = async (data: { dirId: number; dirName: string }) => {
    let datas = {
      dirId: data.dirId,
      pageNum: pageNum.value,
      pageSize: pageSize.value,
    };
    // 接口  selectDir
    console.log('我在这里', datas);
    const resselectDirData = await selectDirData(datas);
    message.success('切换到' + data.dirName + '接口');
    dataSource.value = resselectDirData.data.records;
    // console.log('res', resselectDirData);
    //记住当前所在接口分类的Id
    dirIds.value = data.dirId;
  };

  // （批量）发布，（批量）停用 ，分类 等开始
  //批量发布
  // let portsId1: Ref<number[]> = ref([]);
  const allIssue = async () => {
    activeClass1.value = true;
    //  接口状态(1:未发布;2:已发布;3:已停用)
    let data = {
      portsId: selectedRowKeys1.value,
      portsStatus: 2,
      dirId: dirIds.value,
    };
    arrIssue.value.forEach((i: number) => {
      dataSource.value.forEach(item => {
        if (i == item.portsId) {
          item.portsStatus = 2;
        }
      });
    });
    // 接口
    const res = await pauseAndIssueAllStatus(data);
    selectedRowKeys1.value = [];
  };

  //批量停用
  const allpause = async () => {
    activeClass2.value = true; //停用按钮变为禁用
    let data = {
      portsId: selectedRowKeys1.value,
      portsStatus: 3,
      dirId: dirIds.value,
    };
    arrIssue.value.forEach((i: number) => {
      dataSource.value.forEach(item => {
        if (i == item.portsId) {
          item.portsStatus = 3;
        }
      });
    });
    //接口
    const res = await pauseAndIssueAllStatus(data);
    selectedRowKeys1.value = [];
  };
  //数据删除
  const confirm1 = (portsId: number) => {
    dataSource.value = dataSource.value.filter(item => item.portsId !== portsId);
    delData({ portsId }).then((res: any) => {
      if (res.code == 100200) {
        message.success('删除成功！');
      } else {
        message.error(res.msg);
      }
    });
  };

  //发布
  let porId: Ref<number[]> = ref([]);
  const confirm2 = async (portsId: number) => {
    porId.value.push(portsId);
    let data = {
      portsId: porId.value,
      portsStatus: 2,
      dirId: dirIds.value,
    };
    dataSource.value.filter(item => {
      if (item.portsId == portsId) {
        item.portsStatus = 2;
      }
    });
    const res = await pauseAndIssueAllStatus(data);
    selectedRowKeys1.value = [];

    message.success('发布成功！');
  };

  //停用
  const confirm3 = async (portsId: number) => {
    porId.value.push(portsId);
    let data = {
      portsId: porId.value,
      portsStatus: 3,
      dirId: dirIds.value,
    };
    // 接口
    dataSource.value.filter(item => {
      if (item.portsId == portsId) {
        item.portsStatus = 3;
      }
    });
    const res = await pauseAndIssueAllStatus(data);
    selectedRowKeys1.value = [];

    message.success('停用成功！');
  };

  // 分页
  let pagination = {
    defaultPageSize: 5,
    showTotal: (total: number) => `共 ${total} 条`,
    showSizeChanger: true,
    showQuickJumper: true,
    position: ['bottomCenter'],
    pageSizeOptions: ['5', '10', '15', '20'],
    onShowSizeChange: (_current: number, pageSize: number) => pageSize,
  };
</script>
<style lang="less" scoped>
  .root {
    display: flex;
    flex-direction: row;

    .tree {
      flex: 2;
    }

    .body-wrapper {
      flex: 9;

      .bodyTop {
        display: flex;
        margin-top: 20px;
        margin-bottom: 30px;
        width: 90%;

        .bodyTop2 {
          position: absolute;
          display: flex;
          margin-top: 50px;
        }

        .select {
          display: flex;
          width: 200px;
          height: 40px;
          line-height: 40px;

          .ant-select {
            margin-left: 5px;
          }

          .ant-input {
            margin-left: 5px;
            width: 120px;
            height: 32px;
          }
        }

        .ant-btn-primary {
          border: none;
          background-color: rgb(49, 149, 216) !important;
        }

        .activeClass {
          color: aliceblue;
          background-color: #3195d8 !important;
        }

        .ant-btn-primary:not(.ant-btn-primary:nth-child(7)) {
          margin-top: 25px;
        }

        .editable-cell:hover .editable-cell-icon {
          display: inline-block;
        }
      }

      .relative {
        /deep/ .ant-table {
          min-height: 60vh;
        }
      }

      .operate {
        margin: 2px;
        background-color: rgb(49, 149, 216) !important;
      }
    }

    .ant-btn {
      margin: 1px;
      border-radius: 5px;
    }

    #btn {
      position: absolute;
      margin-top: 71px;
      margin-left: 300px;
    }

    #btn2 {
      margin-top: 4px;
    }
  }
</style>
